/*
 SAMPLE FORM
*/
var qs = require('querystring');

require('./common');


exports.load = function(req, res){
	
	var strSQL = "SELECT FormName, Name, Description, Content FROM tblworkspace WHERE ID = '" + req.params.ID + "' ";
	var requestID = req.params.requestID;
	var content, name, description, formName;
	
	conn.query(strSQL, function(err, results, fields){
		if(err) throw err;
		
		for (var index in results) {
			formName = results[index].FormName;
			content = results[index].Content;
			name = results[index].Name;
			description = results[index].Description;
		}
		
		res.render("form",{
			title: formName,
			name: name,
			content: content,
			description: description,
			requestID: requestID
		});
	});

}

exports.save = function(req, res){

	var tblName = req.body.tblName;
	var strSQL = "SELECT COLUMN_NAME FROM information_schema.columns where table_name='" + tblName +"'";
	var fieldName = new Array();
	
	conn.query(strSQL, function(err, results, fields){
		if(err) throw err;
		
		for (var index in results) {
			fieldName[fieldName.length] = results[index].COLUMN_NAME;
		}
		
		console.log(fieldName.join());
		
		insertRecord(tblName,fieldName, req);
		res.redirect('/');
	});
	
}


function insertRecord(tblName, fields, req){
	var createSQL = "INSERT INTO " + tblName + " ( ";
	
	for(var ctr=1;ctr<fields.length;ctr++){
		if(ctr<fields.length-1){
		createSQL += fields[ctr] + ", ";
		}else{
		createSQL += fields[ctr] + "";
		}
	}
	
	createSQL+=") VALUES (";
	
	for(var ctr=1;ctr<fields.length;ctr++){
		if(ctr<fields.length-1){
		createSQL += "'" + req.param(fields[ctr],null) + "', ";
		}else{
		createSQL += "'" + req.param(fields[ctr],null) + "' ";
		}
	}
	
	createSQL+=")";
	
	//console.log(createSQL);
	console.log("INSERTING RECORD...." + tblName);
	conn.query(createSQL);
	console.log("Done INSERTING RECORD..." + tblName);
}